/**
 * 拥有Remote page功能的表格.
 *
 * @see CQCIS.grid.ListGrid
 * @author liuhz
 */
CQCIS.grid.PageGrid = Ext.extend(CQCIS.grid.ListGrid, {
    /**
     * @cfg {dwr} DWR call DWR方法
     *
     * <pre>
     * ---------------------------
     * call     page call              DWR PAGE方法
     * config   {filter, like, sort}   是否执行过滤
     * exportPage                      导出Excel页面
     * exportClass                     导出Excel类
     * exportMethod                    导出Excel方法
     * </pre>
     */
    /**
     * @cfg {id, data, total} pagemeta 与数据库Page对应的属性设置
     */
    pageSize: 20,
    // private
    initBbar: function(){
        if (this.bbar !== false) {
            var grid = this;
            this.bbar = new Ext.PagingToolbar({
                firstText: "第一页 (<b>ctrl + Home</b>)",
                prevText: "前一页 (<b>alt + &lt;</b>)",
                nextText: "下一页 (<b>alt + &gt;</b>)",
                lastText: "最后页 (<b>ctrl + End</b>)",
                refreshText: "刷新 (<b>alt + R</b>)",
                beforePageText: "第",
                afterPageText: "页, 共{0}页",
                displayMsg: '显示 {0}-{1}, 共 {2} 条',
                emptyMsg: "没有符合条件的记录",
                store: this.ds,
                pageSize: this.pageSize,
                displayInfo: true,
                onRender: function(ct, position){
                    Ext.PagingToolbar.superclass.onRender.call(this, ct, position);
                    this.first = this.addButton({
                        tooltip: this.firstText,
                        iconCls: "x-tbar-page-first",
                        disabled: true,
                        handler: this.onClick.createDelegate(this, ["first"])
                    });
                    this.prev = this.addButton({
                        tooltip: this.prevText,
                        iconCls: "x-tbar-page-prev",
                        disabled: true,
                        handler: this.onClick.createDelegate(this, ["prev"])
                    });
                    this.addSeparator();
                    this.add(this.beforePageText);
                    this.field = Ext.get(this.addDom({
                        tag: "input",
                        type: "text",
                        size: "3",
                        value: "1",
                        cls: "x-tbar-page-number"
                    }).el);
                    this.field.on("keydown", this.onPagingKeydown, this);
                    this.field.on("focus", function(){
                        this.dom.select();
                    });
                    this.afterTextEl = this.addText(String.format(this.afterPageText, 1));
                    this.field.setHeight(18);
                    this.addSeparator();
                    this.next = this.addButton({
                        tooltip: this.nextText,
                        iconCls: "x-tbar-page-next",
                        disabled: true,
                        handler: this.onClick.createDelegate(this, ["next"])
                    });
                    this.last = this.addButton({
                        tooltip: this.lastText,
                        iconCls: "x-tbar-page-last",
                        disabled: true,
                        handler: this.onClick.createDelegate(this, ["last"])
                    });
                    this.addSeparator();
                    this.loading = this.addButton({
                        text: '刷新',
                        disabled: true,
                        tooltip: this.refreshText,
                        iconCls: "btn_refresh",
                        handler: this.onClick.createDelegate(this, ["refresh"])
                    });
                    
                    if (this.displayInfo) {
                        this.displayEl = Ext.fly(this.el.dom).createChild({
                            cls: 'x-paging-info'
                        });
                    }
                    if (this.dsLoaded) {
                        this.onLoad.apply(this, this.dsLoaded);
                    }
                },
                extendFun: function(){
                    var store = new Ext.data.SimpleStore({
                        fields: ['pageSize'],
                        data: [[10], [20], [25], [30], [40], [50], [60], [80], [100]]
                    });
                    var combo = new Ext.form.ComboBox({
                        store: store,
                        displayField: 'pageSize',
                        editable: false,
                        typeAhead: false,
                        mode: 'local',
                        value: this.pageSize,
                        triggerAction: 'all',
                        selectOnFocus: true,
                        disabled: true,
                        width: 45,
                        listWidth: 45
                    });
                    this.pageSizeCombo = combo;
                    
                    var pageNo = this.field;
                    this.add('-', '页大小', combo);
                    if (grid.exportPage) {
                        var pgt = this;
                        top.extForm = top.extForm || top.exportXls.getContent().document.getElementById("outForm");
                        this.outBtn = new Ext.Button({
                            tooltip: '导出为Excel文件 (<b>ctrl + alt + S</b>)',
                            iconCls: 'btn_excel',
                            disabled: true,
                            handler: function(){
                                if (top.exportXls) {
                                    var pageData = pgt.getPageData();
                                    var typeForm = new CQCIS.form.WinForm({
                                        buttons: [{
                                            text: '确定',
                                            handler: function(){
                                                typeForm.save();
                                            }
                                        }, {
                                            text: '取消',
                                            handler: function(){
                                                typeForm.hide();
                                            }
                                        }],
                                        listeners: {
                                            'hide': function(o){
                                                o.destroy();
                                            }
                                        },
                                        closeAction: 'close',
                                        width: 200,
                                        height: 220,
                                        title: '请选择导出的范围',
                                        items: [new CQCIS.form.DWRForm({
                                            labelWidth: 70,
                                            fieldWidth: 70,
                                            listeners: {
                                                'beforesave': function(o){
                                                    var radios = o.findByType('radio');
                                                    for (var i = 0; i < radios.length; i++) {
                                                        if (radios[i].getValue()) {
                                                            top.extType = i;
                                                            break;
                                                        }
                                                    }
                                                    top.extForm.action = "xls/" + grid.exportPage + ".jsp";
                                                    var empObj = {};
                                                    top.extForm.elements['filter'].value = CQCIS.toString(grid.getStore().baseParams.filter || empObj, true);
                                                    top.extForm.elements['like'].value = CQCIS.toString(grid.getStore().baseParams.like || empObj, true);
                                                    top.extForm.elements['sort'].value = CQCIS.toString(grid.getStore().baseParams.sort || empObj, true);
                                                    top.extForm.elements['pageNo'].value = pageNo.getValue();
                                                    top.extForm.elements['pageSize'].value = combo.getValue();
                                                    top.extForm.elements['extType'].value = top.extType;
                                                    top.extForm.elements['totalCount'].value = grid.getStore().getTotalCount() || 0;
                                                    top.extForm.elements['startPage'].value = o.findField('startPage').getValue() || 0;
                                                    top.extForm.elements['endPage'].value = o.findField('endPage').getValue() || 0;
                                                    top.extForm.submit();
                                                    o.ownerCt.close();
                                                    return false;
                                                },
                                                scope: this
                                            },
                                            metas: [{
                                                field: 'extType_radio',
                                                desc: '导出当前页',
                                                xtype: 'radio',
                                                obj: {
                                                    id: 'extTypeA',
                                                    value: 0,
                                                    checked: !top.extType || top.extType == 0
                                                }
                                            }, {
                                                field: 'extType_radio',
                                                desc: '导出全部',
                                                xtype: 'radio',
                                                obj: {
                                                    id: 'extTypeB',
                                                    value: 1,
                                                    checked: top.extType == 1
                                                }
                                            }, {
                                                field: 'extType_radio',
                                                desc: '导出范围',
                                                xtype: 'radio',
                                                obj: {
                                                    id: 'extTypeC',
                                                    value: 2,
                                                    checked: top.extType == 2
                                                }
                                            }, {
                                                field: 'startPage',
                                                desc: '起始页数',
                                                xtype: 'num',
                                                obj: {
                                                    disabled: top.extType !== 2,
                                                    validator: function(val){
                                                        return val > pageData.pages ? "起始页数不能大于总页数" : val < 1 ? "起始页数不能小于 1 " : true;
                                                    },
                                                    value: top.extForm.elements['startPage'].value || pageData.activePage
                                                }
                                            }, {
                                                field: 'endPage',
                                                desc: '截止页数',
                                                xtype: 'num',
                                                obj: {
                                                    disabled: top.extType !== 2,
                                                    validator: function(val){
                                                        var startPage = typeForm.form.findField('startPage').getValue();
                                                        return val < startPage ? "截止页数不能小于起始页数" : val > pageData.pages ? "截止页数不能大于总页数" : true;
                                                    },
                                                    value: top.extForm.elements['endPage'].value || pageData.pages
                                                }
                                            }]
                                        })]
                                    });
                                    typeForm.show(true);
                                    Ext.each(document.getElementsByName('extType_radio'), function(o){
                                        Ext.get(o).on('click', function(e, obj){
                                            typeForm.form.findField('startPage').setDisabled(obj.id != 'extTypeC');
                                            typeForm.form.findField('endPage').setDisabled(obj.id != 'extTypeC');
                                        });
                                    });
                                }
                            }
                        });
                        this.add(this.outBtn);
                    }
                    this.field.set({
                        disabled: true
                    });
                    combo.on("select", function(c, record){
                        this.pageSize = parseInt(c.getValue());
                        //grid.reload();
                        this.doLoad(0);
                    }, this);
                    this.store.on('load', function(){
                        combo.setDisabled(this.store.getCount() == 0);
                        this.field.set({
                            disabled: this.store.getCount() == 0
                        });
                        //this.loading.setDisabled(this.store.getCount() == 0);
                        if (this.outBtn) {
                            this.outBtn.setDisabled(this.store.getCount() == 0);
                        }
                    }, this);
                    
                    this.first.KeyMap = new Ext.KeyMap(document, {
                        key: 36,
                        //alt : true,
                        ctrl: true,
                        fn: this.onClick.createDelegate(this, ["first"])
                    });
                    this.last.KeyMap = new Ext.KeyMap(document, {
                        key: 35,
                        //alt : true,
                        ctrl: true,
                        fn: this.onClick.createDelegate(this, ["last"])
                    });
                    this.prev.KeyMap = new Ext.KeyMap(document, {
                        key: 188,
                        alt: true,
                        //ctrl : true,
                        fn: this.onClick.createDelegate(this, ["prev"])
                    });
                    this.next.KeyMap = new Ext.KeyMap(document, {
                        key: 190,
                        alt: true,
                        //ctrl : true,
                        fn: this.onClick.createDelegate(this, ["next"])
                    });
                    this.loading.KeyMap = new Ext.KeyMap(document, {
                        key: 'R',
                        alt: true,
                        //ctrl : true,
                        fn: this.onClick.createDelegate(this, ["refresh"])
                    });
                }
            });
        }
    },
    
    // private
    initDs: function(){
        if (!this.ds && this.recordHeaders) {
            this.ds = new Ext.data.Store({
                proxy: new CQCIS.data.DWRPageProxy(this.dwr.call, this.dwr.config, this),
                reader: new CQCIS.data.DWRPageReader(this.pagemeta, this.recordHeaders),
                remoteSort: true
            });
            delete this.recordHeaders;
        }
    },
    // overwrite
    onRender: function(ct, position){
        this.filter = this.filter ||
        {};
        this.like = this.like ||
        {};
        
        CQCIS.grid.PageGrid.superclass.onRender.call(this, ct, position);
        var bbar = this.getBottomToolbar();
        if (bbar.extendFun) {
            bbar.extendFun();
        }
        
    //this.setHeight(Ext.isIE6 ? top.center.body.getSize().height - 7 : top.center.body.getSize().height - 8);
    },
    
    /**
     * 刷新Grid,加载数据
     */
    reload: function(){
        var a = arguments || {}, lo = this.store.lastOptions || {}, pn = lo.params || {};
        a.params = Ext.applyIf(a.params || {}, {
            start: 0,
            limit: pn.limit
        });
        this.store.reload(a);
    }
});
Ext.reg('pgrid', CQCIS.grid.PageGrid);
